package com.atguigu.lease.web.admin.custom.interceptors;

import com.aliyun.dysmsapi20170525.Client;
import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.jwts.JwtUtil;
import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取request中请求头的token [access_token]
        String accessToken = request.getHeader("access_token");
        //2.检查token是否为null
        if (ObjectUtils.isEmpty(accessToken)){
            //没有token 没有登陆
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);

        }
        //3.检查token是否过期和有效
        Claims claims =  JwtUtil.parseToken(accessToken);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUserHolder.setLoginUser(new LoginUser(userId,username));
        //true放行 | false拦截[if(!preHandler() ) return ;]

        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }

}
